package com.servlet.form;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.listener.ContextListener;
import com.servlet.model.database.BaseAcces;
import com.servlet.model.database.BaseAccesImpl;

public class ProfilPhotoForm extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		boolean correct = false;

		HttpSession session = request.getSession();
		String email = (String) session.getAttribute("email");
		System.out.println(email);
		BaseAcces base = ContextListener.base;
		
		String resultat = null;
		boolean chargementPhotoOk = false;
		
		try {
			// Check that we have a file upload request
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (isMultipart) {
				// Create a factory for disk-based file items
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				// Create a new file upload handler
				// Parse the request
				List items;
				items = upload.parseRequest(request);
				// Process the uploaded items
				Iterator iter = items.iterator();
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();
					// si c'est différent d'un autre champ du formulaire :
					// submit par exemple
					if (!item.isFormField()) {
						//on vérifie le type du fichier
						if (item.getContentType().compareTo("image/jpeg") == 0) {
							//on vérifie la taille de l'image
							if(item.getSize() <= 524288){
								//id du profil qui va permettre de nommer l'image
								int id = base.findProfile(email).getId();
								//a present on va composer le nom de la photo avec l'adresse email et l'extension
								File savedFile = new File("./webapps/Propig/files/photos/photo" + id + ".jpeg");
								item.write(savedFile);
								resultat = "Photo chargée";
								chargementPhotoOk = true;
							}
							else{
								resultat = "L'image ne peut excéder 500Ko";
							}
						}
						else{
							resultat = "Le fichier envoyé n'est pas une image";
						}
					}
				}
			} else {
				resultat = "Le contenu n'est pas de type Multipart";
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultat = "Erreur d'extraction de l'image";
		}
		session.setAttribute("resultat", resultat);
		if(chargementPhotoOk)
		{
			response.sendRedirect("profil");
		}
		else{
			System.out.println(resultat);
			response.sendRedirect("profilPhoto");
		}
	}
}
